<?php

namespace app\common\logic\common;

use app\common\helper\NetPay;
use app\common\logic\BaseLogic;
use app\common\model\ExpressOrder;
use app\common\model\GroupOrder;
use app\common\model\Order;
use app\common\model\Pay;
use app\common\model\Refund;
use app\common\model\VipOrder;
use think\helper\Str;

class PayLogic extends BaseLogic
{
    public static function createOrUpdatePayOrder($order_id)
    {
        // 生成定金支付
        $order = VipOrder::find($order_id);
        $pay = Pay::where("order_id",$order_id)->find();
        if ($order['money'] <= 0) return 0;
        if (!$pay) {
            $pay = Pay::create([
                "user_id" => $order['user_id'],
                "money" => $order['money'],
                "order_id" => $order_id,
                "out_trade_no" => CommonLogic::makeOrderNo(),
                "status" => -1
            ]);
        } else {
            $pay->save([
                "out_trade_no" => CommonLogic::makeOrderNo(),
            ]);
        }
        return $pay->id;
    }
    
    // 微信退款
    public static function refund($order)
    {
        $order = GroupOrder::where("id",$order['id'])->find();
        if (!$order || $order->status < 1) {
            throwError('订单错误');
        }
        if ($order->is_refunded == 1) throwError('订单已经退款');
        $refund_trade_no = CommonLogic::makeOrderNo();
        $pay = \app\common\model\Pay::where("order_id",$order['id'])->find();
        Refund::create([
            "order_id" => $order['id'],
            "refund_trade_no" => $refund_trade_no,
            "out_trade_no" => $pay->out_trade_no,
            "money" => $pay->money,
            "user_id" => $pay->user_id
        ]);
        $payObj = new NetPay();
        return $payObj->createWxRefund($refund_trade_no,$pay->out_trade_no,$pay->money,$pay->money );
    }
}